
// Definition for a binary tree node.
class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val===undefined ? 0 : val)
        this.left = (left===undefined ? null : left)
        this.right = (right===undefined ? null : right)
    }
}


function invertTree(root: TreeNode | null): TreeNode | null {
    const stack_arr = [root];
    while(stack_arr.length > 0)
    {
        const tmp_arr = stack_arr.reverse();
        stack_arr.length = 0; // clear the array
        for(let i = 0; i < tmp_arr.length; i++)
        {
            const node = tmp_arr[i];
            if(node === null)
            {
                continue;
            }
            const tmp = node.left;
            node.left = node.right;
            node.right = tmp;
            stack_arr.push(node.left);
            stack_arr.push(node.right);
        }
    }
    return root;
};
